"""
参数分类管理模块路由
"""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from ..db import get_db
from ..schemas import (
    ParameterCategory, ParameterCategoryCreate, ParameterCategoryUpdate, MessageResponse
)
from ..db.parameters.crud import (
    create_parameter_category, get_parameter_category_by_name_en,
    get_parameter_categories, update_parameter_category, delete_parameter_category,
    get_project_by_name_en
)

router = APIRouter(prefix="/api/projects/{project_name_en}/categories", tags=["参数分类管理"])


@router.post("", response_model=ParameterCategory, status_code=201)
async def create_parameter_category_endpoint(
    project_name_en: str,
    category: ParameterCategoryCreate,
    db: Session = Depends(get_db)
):
    """创建参数分类"""
    # 检查项目是否存在
    project = get_project_by_name_en(db, project_name_en)
    if not project:
        raise HTTPException(
            status_code=404,
            detail=f"项目 '{project_name_en}' 不存在"
        )
    
    # 检查分类英文名称是否已存在
    existing_category = get_parameter_category_by_name_en(db, project.id, category.name_en)
    if existing_category:
        raise HTTPException(
            status_code=400,
            detail=f"分类英文名称 '{category.name_en}' 已存在"
        )
    
    return create_parameter_category(db, category, project.id)


@router.get("")
async def get_parameter_categories_endpoint(project_name_en: str, db: Session = Depends(get_db)):
    """获取参数分类列表"""
    # 检查项目是否存在
    project = get_project_by_name_en(db, project_name_en)
    if not project:
        raise HTTPException(
            status_code=404,
            detail=f"项目 '{project_name_en}' 不存在"
        )
    
    categories = get_parameter_categories(db, project.id)
    # 手动转换为字典
    result = []
    for cat in categories:
        result.append({
            "id": cat.id,
            "name": cat.name,
            "name_en": cat.name_en,
            "description": cat.description,
            "sort_order": cat.sort_order,
            "project_id": cat.project_id,
            "created_at": cat.created_at.isoformat() if cat.created_at else None,
            "updated_at": cat.updated_at.isoformat() if cat.updated_at else None
        })
    return result


@router.put("/{category_name_en}", response_model=ParameterCategory)
async def update_parameter_category_endpoint(
    project_name_en: str,
    category_name_en: str,
    category_update: ParameterCategoryUpdate,
    db: Session = Depends(get_db)
):
    """更新参数分类"""
    # 检查项目是否存在
    project = get_project_by_name_en(db, project_name_en)
    if not project:
        raise HTTPException(
            status_code=404,
            detail=f"项目 '{project_name_en}' 不存在"
        )
    
    # 检查分类是否存在
    category = get_parameter_category_by_name_en(db, project.id, category_name_en)
    if not category:
        raise HTTPException(
            status_code=404,
            detail=f"分类 '{category_name_en}' 不存在"
        )
    
    updated_category = update_parameter_category(db, category.id, category_update)
    return updated_category


@router.delete("/{category_name_en}", response_model=MessageResponse)
async def delete_parameter_category_endpoint(
    project_name_en: str,
    category_name_en: str,
    db: Session = Depends(get_db)
):
    """删除参数分类"""
    # 检查项目是否存在
    project = get_project_by_name_en(db, project_name_en)
    if not project:
        raise HTTPException(
            status_code=404,
            detail=f"项目 '{project_name_en}' 不存在"
        )
    
    # 检查分类是否存在
    category = get_parameter_category_by_name_en(db, project.id, category_name_en)
    if not category:
        raise HTTPException(
            status_code=404,
            detail=f"分类 '{category_name_en}' 不存在"
        )
    
    success = delete_parameter_category(db, category.id)
    if success:
        return MessageResponse(message=f"分类 '{category_name_en}' 删除成功")
    else:
        raise HTTPException(
            status_code=500,
            detail="删除分类失败"
        )

